import java.io.File;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

public class Main {

	public static void main(String[] args) throws Exception {

		HashMap<String, PrintWriter> pws = new HashMap<String, PrintWriter>();

		/*
		 * Verify that user has provided input file
		 */
		if (args.length < 1) {
			System.err.println("Provide input file");
			System.exit(1);
		}

		/*
		 * Input file (miny-pascal source code)
		 */
		String path = args[0];

		/*
		 * Retrieving parsing service
		 */
		parser myParser = parser.getParser(path);

		/*
		 * Retrieving the AST object
		 */
		Node root = null;
		System.out.println(myParser.getTree());

		try {
			root = myParser.getTree();
		} catch (Exception e) {
			e.printStackTrace();
		}

		/*
		 * Extracting the input file name without extension
		 */
		int startPos = path.lastIndexOf(File.separator);
		int endPos = path.lastIndexOf(".");
		if (endPos <= startPos) {
			endPos = path.length();
		}
		String nameWithoutExtension = path.substring(0, endPos);

		/*
		 * Output AST contents (pre-order)
		 */
		// String ASTFileName = nameWithoutExtension + ".ast.txt";
		// PrintWriter ast_pw = new PrintWriter(ASTFileName);
		// System.out.println("printing AST tree [" + ASTFileName + "]");
		// if (ast_pw == null) {
		// System.out.println("ast_pw is null...");
		// }
		SymbolTable st = new SymbolTable();
		root.translate(pws, null, st, "");
		// ast_pw.close();
		Collection<PrintWriter> results = pws.values();

		for (Iterator<PrintWriter> it = results.iterator(); it.hasNext();) {
			PrintWriter pw = it.next();
			pw.close();
		}

		for (int i = 0; i < st.getTables().size(); i++) {
			System.out.println("--------------------------------------");
			Symbol temp = st.getTables().get(i);
			System.out.println("type: " + temp.getType().getName());
			System.out.println("name: " + temp.getName());
			if (temp.getParent() != null) {
				System.out.println("parent: " + temp.getParent());
			} else {
				System.out.println("parent: null");
			}

			for (int j = 0; j < temp.getScopes().size(); j++) {
				System.out
						.println("scope" + j + ": " + temp.getScopes().get(j));
			}
		}

		st.getStack().pop();

		/*
		 * End
		 */
		System.out.println("Translated Successfully.");
	}
}
